package com.ruoyi.system.controller;

/**
 * @author Wangbj
 * @date 2024年04月19日 14:03
 */
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.InputStream;
import java.net.URI;

import java.io.File;
import java.io.InputStream;
@RestController
@RequestMapping("oss")
@Slf4j
public class OSSUploadController {

    @Value("${OSS.ENDPOINT}")
    private String ENDPOINT;

    @Value("${OSS.ACCESS_KEY_ID}")
    private String ACCESS_KEY_ID;

    @Value("${OSS.ACCESS_KEY_SECRET}")
    private String ACCESS_KEY_SECRET;

    @Value("${OSS.BUCKET_NAME_OPEN}")
    private String bucketName;


    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 创建OSSClient对象
            OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            // 上传文件到OSS
            String objectName = System.currentTimeMillis()+file.getOriginalFilename(); // 可以自定义上传后的文件名
            InputStream inputStream = file.getInputStream();
            PutObjectResult putObjectResult = ossClient.putObject(new PutObjectRequest(bucketName, objectName, inputStream));
            log.info("文件上传成功：【{}】",objectName);
            // 关闭OSSClient
            ossClient.shutdown();

            return ResponseEntity.ok(objectName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件上传失败：【{}】" + e.getMessage());
        }
    }
    @GetMapping("/download/{fileName}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) {
        try {
            // 创建OSSClient对象
            OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            // 指定Bucket名称和文件名称
            OSSObject ossObject = ossClient.getObject(bucketName, fileName);

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 读取OSSObject的InputStream并封装为InputStreamResource
            InputStream inputStream = ossObject.getObjectContent();
            InputStreamResource resource = new InputStreamResource(inputStream);
            log.info("文件下载成功：【{}】",fileName);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/preview/{fileName:.+}")
    public ResponseEntity<InputStreamResource> previewFile(@PathVariable String fileName) {
        try {
            // 创建OSSClient对象
            OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            // 指定Bucket名称和文件名称
            OSSObject ossObject = ossClient.getObject(bucketName, fileName);

            // 获取图片的InputStream
            InputStream inputStream = ossObject.getObjectContent();

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            // 根据文件扩展名设置Content-Type
            String contentType = getContentType(fileName);
            headers.add("Content-Type", contentType);

            log.info("查看文件：【{}】",fileName);

            // 创建InputStreamResource并返回
            InputStreamResource resource = new InputStreamResource(inputStream);
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        } finally {
            // 关闭OSSClient（如果适用）
            // ossClient.shutdown(); // 通常不需要手动关闭，因为OSSClient是线程安全的，可以重用
        }
    }

    // 根据文件名推测Content-Type
    private String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("png".equalsIgnoreCase(fileExtension)) {
            return "image/png";
        } else if ("jpg".equalsIgnoreCase(fileExtension) || "jpeg".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        } else if ("gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        // 可以根据需要添加更多文件类型
        return "application/octet-stream"; // 默认类型
    }
}
